package plat

import (
	"time"
	"fmt"
	"encoding/json"
	"strconv"
	"errors"
	"publish/app/account/model"
)

func init() {
	RegisterPlat("kuaichuan", newplat_kuaichuan())
}

type platkuaichuan struct {
	*plathttp
}


func newplat_kuaichuan() Plat {
	return &platkuaichuan{
		plathttp: &plathttp{
			Host: "https://kuaichuan.360.cn",
		},
	}
}

func (p *platkuaichuan) GetEveryStatistic(account *model.Account,start,end time.Time)([]EveryDayStatisttic, error){
	return nil,nil
}

func (p *platkuaichuan) GetProfit(account *model.Account, start, end time.Time) ([]AccountProfit, error) {
	return nil,nil
}

func (p *platkuaichuan) GetIndex(account *model.Account, start, end time.Time) ([]AccountData, error) {
	indexs := KCIndexResp{}
	scores := KCScoreResp{}

	{
		apiIndex := `http://kuaichuan.360.cn/data/getMainCateRank`
		p.setCookie(account.GetCookie())
		body, err := p.getReq(apiIndex)
		if err != nil {
			return nil, err
		}
		err = json.Unmarshal(body, &indexs)
		if err != nil {
			return nil, err
		}
		if indexs.Errno != 0 {
			return nil, errors.New(fmt.Sprintf("get profit return , account_id = %d, errorms = %s", account.Id, indexs.Msg))
		}
	}


	{
		apiIndex := `http://kuaichuan.360.cn/data/getMainCateScore`
		p.setCookie(account.GetCookie())
		body, err := p.getReq(apiIndex)
		if err != nil {
			return nil, err
		}
		err = json.Unmarshal(body, &scores)
		if err != nil {
			return nil, err
		}
		if indexs.Errno != 0 {
			return nil, errors.New(fmt.Sprintf("get profit return , account_id = %d, errorms = %s", account.Id, indexs.Msg))
		}
	}

	rets := make([]AccountData, 0)
	rets = append(rets, AccountData{
		AccountId: account.Id,
		Index:     strconv.Itoa(indexs.Data.Total),
		Time:      time.Now().Format("2006-01-02 15:04:05"),
		Date:      scores.Data.UpdateTime,
		IndexJson: map[string]interface{}{
			"total":      indexs.Data.Total,
			"favorite":   scores.Data.Quality,
			"creativity": scores.Data.Productivity,
			"activity":   scores.Data.Popularity,
			"influence":  scores.Data.Professional,
			"reward":     scores.Data.Credit,
		},
	})

	return rets, nil
}

func (p *platkuaichuan) GetStatistic(account *model.Account, start, end time.Time) ([]AccountStatisttic, error) {
	datas := []AccountStatisttic{}
	news, err := p.getStatisticNews(account, start, end)
	if err != nil {
		fmt.Println("GetStatisticNews:", err.Error())
	} else {
		datas = append(datas, news...)
	}

	videos, err := p.getStatisticVideo(account, start, end)
	if err != nil {
		fmt.Println("GetStatisticVideo :", err.Error())
	} else {
		datas = append(datas, videos...)
	}

	return datas,nil
}

func (p *platkuaichuan) getStatisticNews(account *model.Account, start, end time.Time) ([]AccountStatisttic, error) {
	api := `http://kuaichuan.360.cn/article/analyze?start_time=%s&end_time=%s`
	uk := fmt.Sprintf(api, start.Format("2006-01-02"), end.Format("2006-01-02"))

	p.setCookie(account.GetCookie())
	bodyBytes, err := p.getReq(uk)
	if err != nil {
		return nil, err
	}

	statistic := KCStatisticResp{}
	err = json.Unmarshal(bodyBytes, &statistic)
	if err != nil {
		return nil, err
	}
	datas := []AccountStatisttic{}
	for _, data := range statistic.Data.ArticleList {
		read,_ := strconv.ParseInt( data.ReadNum, 10, 64)
		recommend,_ := strconv.ParseInt( data.RecNum, 10, 64)
		datas = append(datas, AccountStatisttic{
			AccountId: account.Id,
			Num:       read, //阅读量
			Type:      "reads_news",
			Time:      time.Now().Format("2006-01-02 15:04:05"),
			Date:      data.UpdateTime,
		}, AccountStatisttic{
			AccountId: account.Id,
			Num:       recommend, //推荐量
			Type:      "recommends_news",
			Time:      time.Now().Format("2006-01-02 15:04:05"),
			Date:      data.UpdateTime,
		})
	}

	return datas, nil
}

func (p *platkuaichuan) getStatisticVideo(account *model.Account, start, end time.Time) ([]AccountStatisttic, error) {
	api := `http://v.sj.360.cn/mgrvideo/list?begin=%s&end=%s&filter=pub`
	uk := fmt.Sprintf(api, start.Format("2006-01-02"), end.Format("2006-01-02"))

	p.setCookie(account.GetCookie())
	bodyBytes, err := p.getReq(uk)
	if err != nil {
		return nil, err
	}

	statistic := KCStatisticVideoResp{}
	err = json.Unmarshal(bodyBytes, &statistic)
	if err != nil {
		return nil, err
	}
	datas := []AccountStatisttic{}
	for _, data := range statistic.List {
		datas = append(datas, AccountStatisttic{
			AccountId: account.Id,
			Num:       data.Score.Read, //播放量
			Type:      "reads_video",
			Time:      time.Now().Format("2006-01-02 15:04:05"),
			Date:      data.PublishTime,
		}, AccountStatisttic{
			AccountId: account.Id,
			Num:       data.Score.Pv, //推荐量
			Type:      "recommends_video",
			Time:      time.Now().Format("2006-01-02 15:04:05"),
			Date:      data.PublishTime,
		})
	}

	return datas, nil
}

func (p *platkuaichuan) GetLevel(account *model.Account) (string, error) {
	return "",nil
}

func (p *platkuaichuan) GetArticles(account *model.Account, start time.Time, end time.Time) ([]Article, error) {
	articles := []Article{}
	page := 1

	for {
		api := fmt.Sprintf(`http://kuaichuan.360.cn/content/contentList?page=%d`,page)
		p.setCookie(account.GetCookie())
		bodyBytes, err := p.getReq(api)
		if err != nil {
			return nil, err
		}

		datas :=  KCList{}
		if err := json.Unmarshal(bodyBytes,&datas);err != nil{
			return nil,err
		}

		fmt.Println("page:",page)
		fmt.Println("datas:",datas)

		if datas.Errno != 0 || len(datas.Data.List) == 0{
			return articles,nil
		}

		for _,data := range datas.Data.List{
			statusMsg := ""
			status := 0
			if data.Status == "1"{
				status = 3
				statusMsg = "审核中"
			}

			if data.Status == "3"{
				status = 4
				statusMsg = "发布失败"
			}

			if data.Status == "2"{
				status = 1
			}

			t,_ := time.Parse("2006-01-02 15:04:05",data.PublishTime)

			if t.Before(start){
				return articles,nil
			}

			if t.After(start) && t.Before(end) {
				articles = append(articles, Article{
					Title:   data.Title,
					Url:     data.Url,
					Time:    t,
					Status:  status,
					FailMsg: statusMsg,
				})
			}
		}

		if len(datas.Data.List) < 10{
			return articles,nil
		}

		page++
	}
	return articles,nil
}

func (p *platkuaichuan) GetPayRecord(account *model.Account, start time.Time, end time.Time) ([]PayRecord, error) {
	return nil,nil
}

func (p *platkuaichuan) GetFinancialInformation(account *model.Account) (*FinancialInformation, error) {
	return nil,nil
}

